package com.auto.printer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWTUtil;
import com.auto.printer.common.constant.Consant;
import com.auto.printer.common.exception.MyException;
import com.auto.printer.entity.param.MiniUserLoginParam;
import com.auto.printer.entity.po.SysUser;
import com.auto.printer.entity.vo.UserLoginVo;
import com.auto.printer.mapper.SysUserMapper;
import com.auto.printer.service.SysUserService;
import com.auto.printer.utils.CheckUtil;
import com.auto.printer.utils.WxUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @author LoveHuaHua
 * @date 2023年07月25日 10:05
 * @description believe in yourself
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Lazy))
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    /**
     * 默认头像
     */
    private String defaultAvatar = "https://cdn.jxwazx.cn/avatar/default_avatar.jpg";

    /**
     * 微信小程序登录
     *
     * @param miniUserLoginParam 迷你用户登录参数
     * @return {@link String}
     */
    @Override
    public UserLoginVo loginByMini(MiniUserLoginParam miniUserLoginParam) {
        String openId = WxUtil.getOpenId(miniUserLoginParam.getCode());
        CheckUtil.checkStrNotBlank(openId, new MyException("openId为空,登录失败!"));
        //判断openId是否存在
        SysUser sysUser = lambdaQuery().eq(SysUser::getMiniOpenId, openId).one();
        if (ObjUtil.isNull(sysUser)) {
            sysUser = new SysUser();
            sysUser.setAvatar(defaultAvatar);
            sysUser.setStatus(Consant.YesOrNoConstant.YES);
            sysUser.setNickName(StrUtil.format("花花云打印{}", RandomUtil.randomString(5)));
            sysUser.setMiniOpenId(openId);
            save(sysUser);
        }
        UserLoginVo userLoginVo = new UserLoginVo();
        if (sysUser.getStatus().equals(Consant.YesOrNoConstant.NO)){
            //如果是禁用
            userLoginVo.setFlag(Consant.YesOrNoConstant.NO);
            userLoginVo.setMessage("账号被禁用!请联系管理员");
        }else{
            userLoginVo.setFlag(Consant.YesOrNoConstant.YES);
            String token = JWTUtil.createToken(BeanUtil.beanToMap(sysUser), "huahua_printer".getBytes());
            userLoginVo.setToken(token);
        }
        return userLoginVo;
    }
}
